﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Windows.Media;

namespace RaSuperGrid.SuperGrid.Converter
{
    class ContactValueConverter : IValueConverter
    {
        private static readonly Regex _pattern 
                                      = new Regex(@"^                           # Begin

                                                    (?:[\(\+]?)                 # Optional ( or +

                                                    (?<AreaCode>\d{3})          # 3 digit area code

                                                    (?:[\)-]?)                  # Optional ) or -

                                                    (?<PhoneNumber>\d{6,10})    # PhoneNumber

                                                    $                           # End",
                                                  RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

        private static readonly Regex _input
                                      = new Regex(@"^[\(\)\d\+-]+$",
                                                  RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string contact = System.Convert.ToString(value);

            if (IsValidContact(contact))
            {
                return Brushes.Black as Brush;
            }
            else
            {
                return Brushes.Red as Brush;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public static bool IsValidContactInput(string input)
        {
            return (_input.IsMatch(input));
        }

        public static bool IsValidContact(string contact)
        {
            return (_pattern.IsMatch(contact));
        }

        public static bool GetContact(string contact, out string areaCode, out string phoneNumber)
        {
            Match match = _pattern.Match(contact);

            areaCode = match.Groups["AreaCode"].Value;
            phoneNumber = match.Groups["PhoneNumber"].Value;
 
            return (match.Success);
        }
    }
}
